<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/29
 * Time: 13:44
 */

namespace app\api\job;

use think\queue\Job;
use app\common\model\Wallet;
use app\common\model\WalletLog;
use app\common\model\WalletRecord;
use think\Db;

class Paijiang
{

    protected $maxTime = 6;

    public function sendjiangjin(Job $job,$data)
    {
        $isJobDone = $this->doPaijiangJob($data);
        if( $isJobDone ){
            //任务执行成功,删除任务
            $job->delete();
        }else{
            if( $job->attempts() > $this->maxTime ){
                $job->delete();
            }
        }
        unset($data);
    }

    public function doPaijiangJob($data)
    {
        $record_sn = checkRecordSn();
        if( !isset($record_sn) || !$record_sn ){
            $record_sn = date('ymdHis',time()) . mt_rand(1111,9999);
        }
        Db::startTrans();
        try{
            WalletRecord::insert([
                'record_sn' => $record_sn,
                'user_id'   => $data['user_id'],
                'type'      => 4,    //中奖上分
                'money'     => $data['zj_money'],
                'remark'    => '中奖',
                'pay_status'=> 1,
                'pay_time'  => $data['now'],
                'createtime'=> $data['now'],
                'index'     => $data['index']
            ]);
            WalletLog::insert([
                'record_sn' => $record_sn,
                'user_id'   => $data['user_id'],
                'change_money'=> '+'.$data['zj_money'],
                'money'     => Wallet::where('user_id',$data['user_id'])->value('money'),
                'remark'    => '中奖',
                'createtime'=> $data['now'],
                'index'     => $data['index']
            ]);
            Db::commit();
            return true;
        }catch (Exception $e){
            file_put_contents(
                WALLET_ERROR_PATH,
                '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  钱包用户上分异常'.json_encode($e->getMessage()). PHP_EOL,
                FILE_APPEND
            );
            Db::rollback();
            return false;
        }
    }
}